import { app } from 'electron'
import path from 'path'
import fs from 'fs'
import { exec } from 'child_process'
import { ElectronLogger } from '@xmov/electron-extension'
import * as Constants from '../constants/index'

// 当前的可执行文件所在目录
const appPath = app.getPath('exe')
// 获取上一层的目录
// app 是当前目录名称,需要给去掉
const serverPath = path.resolve(appPath, app.isPackaged ? '../server/main' : 'S:/users/huangcheng/smart-ai/server/main')
ElectronLogger.info(`serverPath: ${serverPath}`)
// 本地需要启动的后台服务名称
const cmdStr = `${Constants.AudioServer.WAKEUP_EXE_NAME} --host 0.0.0.0 --port ${Constants.AudioServer.LOCAL_SERVER_PORT} --app_id ${Constants.AudioServer.XF_APP_ID}`
let workerProcess

export const runServer = () => {
  fs.stat(serverPath, function (err: any) {
    if (err) {
      ElectronLogger.error(`[child_process]${Constants.AudioServer.WAKEUP_EXE_NAME} run error:`, err)
    } else {
      runExec(serverPath)
      ElectronLogger.debug(`[child_process]${Constants.AudioServer.WAKEUP_EXE_NAME} running`)
    }
  })
}

function promiseExec(cmd: string) {
  return new Promise((resolve, reject) => {
    exec(cmd, (err: any, data: any) => {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}
export function closeServer(callback?: any) {
  return promiseExec('cmd /c taskkill /f /t /im ' + Constants.AudioServer.WAKEUP_EXE_NAME)
    .then((result: any) => {
      if (typeof result === 'string') {
        ElectronLogger.info(`[child_process]${Constants.AudioServer.WAKEUP_EXE_NAME} killed`)
      }
      if (callback) {
        callback()
      }
    })
    .catch((err: any) => {
      ElectronLogger.error(`[child_process]${err.cmd} failed`)
      if (callback) {
        callback()
      }
    })
}

function runExec(path: string) {
  ElectronLogger.info(cmdStr, { cwd: path })
  workerProcess = exec(cmdStr, { cwd: path })
  workerProcess.stdout.on('data', function (data: any) {
    ElectronLogger.debug('stdout: ' + data)
  })

  workerProcess.stderr.on('data', function (data: any) {
    ElectronLogger.debug('stderr: ' + data)
  })

  workerProcess.on('close', function (code: any) {
    ElectronLogger.debug('out code：' + code)
  })
}
